package com.qingke.memo.command.system;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.qingke.memo.command.SystemCommand;
import com.qingke.memo.pojo.CustomTag;
import com.qingke.memo.pojo.Memo;
import com.qingke.memo.pojo.MemoCustomTag;
import com.qingke.memo.unit.MConsole;

public class SelectMemoByCustomTag extends SystemCommand {

	@Override
	public void execute() {
		Set<CustomTag> setCT=new HashSet<>();
		while(true){
			String condition=MConsole.promptNotEmpty("add condition custom tag(y,n):");
			if("y".equalsIgnoreCase(condition))
				add(setCT);
			else if("n".equalsIgnoreCase(condition))
				break;
			else
				MConsole.println("err input");
		}
		
		List<MemoCustomTag> list=dao.selectAllMemoCustomTags();
		Map<Memo,Set<CustomTag>> map=new HashMap<>();
		for(MemoCustomTag mct:list){
			if(!map.containsKey(mct.getMemo())){
				map.put(mct.getMemo(),new HashSet<CustomTag>());
			}
			map.get(mct.getMemo()).add(mct.getCustomTag());
		}
		
		List<Memo> listM=new ArrayList<>();
		for(Entry<Memo, Set<CustomTag>> entry:map.entrySet()){
			if(entry.getValue().containsAll(setCT))
				listM.add(entry.getKey());
		}
		if(listM.size()==0){
			MConsole.println("no result");
			return ;
		}
		
		Collections.sort(listM, new Comparator<Memo>(){
			@Override
			public int compare(Memo o1, Memo o2) {
				return -o1.getCreateTime().compareTo(o2.getCreateTime());
			}
		});
		MConsole.println("-------memos-------");
		for(Memo m:listM){
			MConsole.println(m.toSimpleString());
		}
		MConsole.println();
		
	}
	private void add(Set<CustomTag> set){
		CustomTag customTag=null;
		while(true){
			String str=MConsole.promptNotEmpty("choose select CustomTag by id or code (id,code):");
			if("id".equalsIgnoreCase(str))
				customTag=byId();
			else if("code".equalsIgnoreCase(str))
				customTag=byCode();
			else{
				MConsole.println("err input");
				continue;
			}
			if(customTag==null)
				return ;
			break;
		}
		if(set.contains(customTag)){
			MConsole.println("the condition has been added.");
			return ;
		}
		set.add(customTag);
	}
	private CustomTag byId(){
		int id=MConsole.getInt("custom tag id:");
		if(!dao.isCustomTagExistById(id)){
			MConsole.println("the custom tag is not existed.");
			return null;
		}
		return dao.selectCustomTagById(id);
	}
	
	private CustomTag byCode(){
		String code=MConsole.promptNotEmpty("custom tag code:");
		if(!dao.isCustomTagExistByCode(code)){
			MConsole.println("the custom tag is not existed.");
			return null;
		}
		return dao.selectCustomTagByCode(code);
	}

}
